package com.xiao.sulinguser.service.impl;

import com.alibaba.nacos.common.utils.StringUtils;
import com.xiao.sulinguser.constant.RedisConstant;
import com.xiao.sulinguser.myenum.RedisEnum;
import com.xiao.sulinguser.service.SmsService;
import com.xiao.sulinguser.sms.Sms;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author: 1322127758@qq.com
 * @date: 2022/3/13 10:11
 * @作用: 发送验证码的逻辑
 */
@Service("smsService")
public class SmsServiceImpl implements SmsService {
    @Autowired
    private Sms sms;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public RedisEnum sendCode(String mobile) {
        /*用户手机号在redis中存的验证码key*/
        String shou = RedisConstant.CODE_USER_REDIS + mobile;

        String s1 = redisTemplate.opsForValue().get(shou);
        /* 判断验证码是否过60秒,没过60秒不能重发 */
        if(!StringUtils.isEmpty(s1)){
            String[] split = s1.split("-");
            if(1 < split.length){
                //获取时间差
                long l = System.currentTimeMillis() - Long.parseLong(split[1]);
                //1分钟
                int i = 1000 * 60;
                if(l < i){
                    //时间还未过60秒
                    return RedisEnum.VERIFY_CODE_EXP;
                }
            }
        }

        //1.创建发送验证码uuid
        String replace = UUID.randomUUID().toString().replace("-", "").substring(0,6);
        //2.保存验证码到redis中
        /*
         * key前缀加手机号
         * value 验证码 + 添加的时间
         * 设置6分钟过期
         */
        String s = replace + "-" + System.currentTimeMillis();
        redisTemplate.opsForValue().set(shou,s,6, TimeUnit.MINUTES);

        //3.发送验证码
        sms.sendCode(mobile,replace);

        return RedisEnum.SEND_CODE_SUCCESS;
    }
}
